﻿using System;
using System.Collections.Generic;
using System.Text;
using com.chttl.ienc.bean;
using System.Text.RegularExpressions;
using java.util;
using java.lang.reflect;
using System.Globalization;

namespace DataAccess
{
    class ToolBox
    {
        public static DataObjectArray getDataObjectArrayFromResponse(String response)
        {
            return (DataObjectArray)((Result)BeanUtil.unmarshallXMLToBean(response, "com.chttl.ienc.bean.DataObjectArray")).getUserData();
        }

        public static Result getResultFromResponse(String response)
        {
            return (Result)BeanUtil.unmarshallXMLToBean(response, "com.chttl.ienc.bean.Result");
        }

        public static T[] getDataArrayFromResponse<T>(string response)
        {
            T[] data = null;
            DataObjectArray array = getDataObjectArrayFromResponse(response);
            data = new T[array.getData().Length];
            int index = 0;
            foreach (DataObject obj in array.getData())
            {
                data[index++] = (T)obj;
            }
            return data;
        }

        public static T getDataFromResponse<T>(string response)
        {
            DataObject obj = getResultFromResponse(response).getUserData();
            return (T)obj;
        }

        /**
         * dateString Format yyyy/MM/dd HH:mm:ss.fff
         * iKVM無java.text.*，無法使用 SimpleDateFormat parse 出 java.util.Date
         * java.util.Date.getTime() 從 1970/01/01 00:00開始，但 System.DateTime.Ticks 從 0001/01/01開始，所以不能 new java.util.Date(DateTime.Ticks)
         * 所以只好用 parse string 方法.
         */
        public static java.util.Date toJavaDate(String dateString)
        {
            //檢查dateString格式
            string re1 = "((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9])\\.([0-9][0-9][0-9]))";	// Time Stamp 1

            Regex r = new Regex(re1,RegexOptions.IgnoreCase|RegexOptions.Singleline);
            Match m = r.Match(dateString);
            if (!m.Success)
            {
                throw new Exception("Format Error");
            }

            string yyyy = dateString.Substring(0, 4);
            string MM = dateString.Substring(5, 2);
            string dd = dateString.Substring(8, 2);
            string HH = dateString.Substring(11, 2);
            string mm = dateString.Substring(14, 2);
            string ss = dateString.Substring(17, 2);
            string fff = dateString.Substring(20, 3);

            java.util.Calendar c = java.util.Calendar.getInstance();
            c.set(java.util.Calendar.YEAR, int.Parse(yyyy));
            c.set(java.util.Calendar.MONTH, (int.Parse(MM) - 1));
            c.set(java.util.Calendar.DAY_OF_MONTH, int.Parse(dd));
            c.set(java.util.Calendar.HOUR_OF_DAY, int.Parse(HH));
            c.set(java.util.Calendar.MINUTE, int.Parse(mm));
            c.set(java.util.Calendar.SECOND, int.Parse(ss));
            //c.set(java.util.Calendar.MILLISECOND, int.Parse(fff));
            c.set(java.util.Calendar.MILLISECOND, 0);

            return c.getTime();
        }

        public static java.util.Date toJavaDate(DateTime date)
        {
            java.util.Calendar c = java.util.Calendar.getInstance();
            c.set(java.util.Calendar.YEAR, date.Year);
            c.set(java.util.Calendar.MONTH, date.Month - 1);
            c.set(java.util.Calendar.DAY_OF_MONTH, date.Day);
            c.set(java.util.Calendar.HOUR_OF_DAY, date.Hour);
            c.set(java.util.Calendar.MINUTE, date.Minute);
            c.set(java.util.Calendar.SECOND, date.Second);
            c.set(java.util.Calendar.MILLISECOND, date.Millisecond);

            return c.getTime();
        }

        /**
         * dateString Format yyyy/MM/dd HH:mm:ss.fff
         */
        public static DateTime toCSharpDate(String dateString)
        {
            return DateTime.ParseExact(dateString, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
        }


        public static DateTime toCSharpDate(Date date)
        {
            java.util.Calendar c = java.util.Calendar.getInstance();
            c.setTime(date);
            DateTime datetime = new DateTime(
                c.get(java.util.Calendar.YEAR), 
                c.get(java.util.Calendar.MONTH) + 1, 
                c.get(java.util.Calendar.DAY_OF_MONTH), 
                c.get(java.util.Calendar.HOUR_OF_DAY), 
                c.get(java.util.Calendar.MINUTE), 
                c.get(java.util.Calendar.SECOND), 
                c.get(java.util.Calendar.MILLISECOND));
            return datetime;
        }

        public static List<object> sort(Set set)
        {
            Iterator itr = set.iterator();
            List<object> list = new List<object>();
            while (itr.hasNext())
            {
                object obj = itr.next();
                list.Add(obj);
            }

            list.Sort(compareById);

            return list;
        }

        private static int compareById(object x, object y)
        {
            java.lang.Object o1 = (java.lang.Object)x;
            java.lang.Object o2 = (java.lang.Object)y;

            string cls1 = o1.getClass().getName();
            string cls2 = o2.getClass().getName();
            if (!cls1.Equals(cls2))
            {
                throw new Exception("Not the same Class!");
            }

            java.lang.Class cls = java.lang.Class.forName(cls1);
            Method getId = cls.getMethod("getId", null);

            int id1 = ((java.lang.Integer)getId.invoke(o1, null)).intValue();
            int id2 = ((java.lang.Integer)getId.invoke(o2, null)).intValue();
            int cmp = 0;

            if (id1 < id2)
            {
                cmp = -1;
            }
            else if (id1 > id2)
            {
                cmp = 1;
            }
            else
            {
                cmp = 0;
            }

            return cmp;
        }


    }


}
